import axios from 'axios'
import Cookies from 'js-cookie'
import CryptoJS from "@/utils/cryptoJs";//加密
import router from '@/router'
import qs from 'qs'
import { clearLoginInfo } from '@/utils'
import isPlainObject from 'lodash/isPlainObject'
//脱敏字段集合 type(姓名 1、手机号 2、身份证 3)
const tmList = [
  { prop: 'card', type: 3 },
  { prop: 'phone', type: 2 },
  { prop: 'passengerPhone', type: 2 },
  { prop: 'rentalcarPhone', type: 2 },
  { prop: 'rentalcarName', type: 1 },
  { prop: 'passengerName', type: 1 },
  { prop: 'realName', type: 1 },
  { prop: 'contactNum', type: 2 },
  { prop: 'linkPerson', type: 1 },
  { prop: 'linkPhone', type: 2 },
  // { prop: 'landlinePhone', type: 2 },
  { prop: 'userName', type: 1 },
  { prop: 'passName', type: 1 },
  { prop: 'credentialNum', type: 3 },
  { prop: 'phoneNum', type: 2 },
  { prop: 'guidePhone', type: 2 },
  { prop: 'guestPhone', type: 2 },
  { prop: 'userPhone', type: 2 },
  { prop: 'touristName', type: 1 },
  { prop: 'touristCode', type: 3 },
  { prop: 'touristPhone', type: 2 },
  { prop: 'linkName', type: 1 },
  { prop: 'linkMobile', type: 2 },
  { prop: 'mobile', type: 2 },
  { prop: 'idCode', type: 3 },
  { prop: 'complainantName', type: 1 },
  { prop: 'complainantPhone', type: 2 },
  { prop: 'idCard', type: 3 },
  { prop: 'guestName', type: 1 },
  { prop: 'checkInName', type: 1 },
  { prop: 'checkInPhone', type: 2 },
  { prop: 'legalPerson', type: 1 },
  { prop: 'operatorCard', type: 3 },
];
var url = '';
const http = axios.create({
  baseURL: window.SITE_CONFIG['apiURL'],
  timeout: 1000 * 180,
  withCredentials: true
})

/**
 * 请求拦截
 */
let urls = ['/sys/user/updateUserPassword', '/sys/user/sendCodeByPhone', '/sys/user/checkCode', '/auth/oauth/token'];
http.interceptors.request.use(config => {
  config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
  if (urls.indexOf(config.url) < 0) {
    config.headers['Authorization'] = 'Bearer ' + Cookies.get('access_token') || ''
  }
  url = config.url;
  // 默认参数
  var defaults = {}
  // 防止缓存，GET请求默认带_t参数
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      ...{ '_t': new Date().getTime() }
    }
  }
  if (isPlainObject(config.params)) {
    config.params = {
      ...defaults,
      ...config.params
    }
  }
  if (isPlainObject(config.data)) {
    config.data = {
      ...defaults,
      ...config.data
    }
    if (/^application\/x-www-form-urlencoded/.test(config.headers['content-type'])) {
      config.data = qs.stringify(config.data)
    }
  }

  // get序列化
  config.paramsSerializer = function (params) {
    return qs.stringify(params, { arrayFormat: 'repeat' })
  }

  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
import Vue from 'vue'
http.interceptors.response.use(response => {
  if (response.data.code === 401 || response.data.code === 10001) {
    clearLoginInfo()
    router.replace({ name: 'login' })
    return Promise.reject(response.data.msg)
  }
  // if (response.data && response.data.data) {
  //   nullToKongStr(response.data.data);
  // }
  let nodeta = false;
  const urls = ['/hotel/homestay/checkInfo/', '/hotel/house/base/getHouseCategoryData/', '/scenic/merchant/info/checkInfo/', '/sys/user/'];
  urls.forEach((item) => {
    if (url.indexOf(item) > - 1) { nodeta = true; return false }
  })
  if (!nodeta) {
    if (url.indexOf('/hotel/order/1') > -1) {
      //房态入住人不脱敏不加密数据备份
      response.data.data.guestName2 = response.data.data.guestName;
      if (response.data.data.detailFormList) {
        let checkInPersonList = response.data.data.detailFormList[0].checkInPersonList;
        if (checkInPersonList.length != 0) {
          checkInPersonList.forEach((ele, i) => {
            ele.checkInName2 = ele.checkInName;
            ele.idCard2 = ele.idCard;
            ele.checkInPhone2 = ele.checkInPhone;
          })
        }
      }
    }
    recursiveModifyField(response.data.data)
  }
  return response
}, error => {
  console.error(error,'error')
  // if(JSON.stringify(error).indexOf('code 403')>-1){
  //   Vue.prototype.$confirm('登录失效,请重新登录', '温馨提示', {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning'
  //   }).then(() => {
  //     clearLoginInfo()
  //     router.replace({ name: 'login' })
  //     return Promise.reject('登录失效,请重新登录')
  //   });
  // }
  return Promise.reject(error)
})
//脱敏规则
function tmRules(value, type) {
  let res = '';
  let regex = '';
  if (type == 1) {
    let arr = Array.from(value)
    if (arr.length === 2) {
      res = arr[0] + '*'
    } else if (arr.length > 2) {
      for (let i = 1; i < arr.length - 1; i++) {
        arr[i] = '*'
      }
      res = arr.join("")
    } else {
      res = value
    }
  } else if (type == 2) {
    regex = /^(.{3})(?:\d+)(.{4})$/;
    if (!regex.test(value)) { res = value } else {
      res = value.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2");
    }
  } else if (type == 3) {
    regex = /^(.{4})(?:\d+)(.{4})$/;
    if (!regex.test(value)) { res = value } else {
      res = value.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2");
    }
  }

  return res;
}
//递归
function recursiveModifyField(obj) {
  // 遍历对象的每个属性
  for (let key in obj) {
    // 如果属性是对象，则递归调用自身
    if(key == "guestPhone"){
      let value =  CryptoJS.decrypt( obj.guestPhone)
      obj.realPhone = value
    }
    if(key == "linkPhone"){
      let value =  CryptoJS.decrypt( obj.linkPhone)
      obj.realPhone = value                 
    }
    if(key == "linkMobile"){
      let value =  CryptoJS.decrypt( obj.linkMobile)
      obj.realPhone = value                 
    }
    if(key == "contactNum"){
      let value =  CryptoJS.decrypt( obj.contactNum)
      obj.realPhone = value                 
    }
    if(key == "credentialNum"){
      let value =  CryptoJS.decrypt( obj.credentialNum)
      obj.realCredentialNum = value                 
    }
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      recursiveModifyField(obj[key]);
    } else {
      let keyName = tmList.filter(item => item.prop == key)[0];
      if (keyName && key === keyName.prop && obj[keyName.prop]) {
        if (CryptoJS.decrypt(obj[keyName.prop]) != '') {
          obj[keyName.prop] = tmRules(CryptoJS.decrypt(obj[keyName.prop]), keyName.type)
        } else {
          obj[keyName.prop] = tmRules(obj[keyName.prop], keyName.type);
        }
      }
      // 如果属性名与要修改的字段名匹配，则用新值替换旧值
      //obj[key] = newValue;
    }
  }
}
//将null和undefined转为空字符串
function nullToKongStr(data){
	if (!data) return;
	let keys = Object.keys(data);
	keys.forEach(k => {
		if(data[k]===null||data[k]===undefined) data[k] = "";
	
		if (typeof data[k] === 'object') {
			nullToKongStr(data[k]);
		} else if (Array.isArray(data[k])) {
			data[k].forEach(dk => {
				if (typeof dk === 'object') {
					nullToKongStr(dk);
				}
			})
		}
	})
}
export default http
